﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using jmail;
using System.Data;

namespace CCOA.App.Message
{
    public partial class ReceiveMail : System.Web.UI.Page
    {
        private string FuncNo = null;
        private void Alert(string msg)
        {
            BP.OA.Debug.Alert(this, msg);
        }
        private string CurUserNo
        {
            get { return BP.Web.WebUser.No; }
        }
        private void DeleteUseLessData()
        {
            BP.OA.Message.Message.DeleteUseLessData();
        }
        public string GetUserNames(object userNos)
        {
            String users = String.Format("{0}", userNos);
            return BP.OA.GPM.GetUserNames(users);
        }
        protected void Page_Init(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                if (!BP.OA.GPM.IsCanUseFun(this.FuncNo)) { BP.OA.GPM.RedirectNoAccess(); return; }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            //if(!IsPostBack)
            //{
            //    RecMail();
            //    Binding(true);
            //}
            if (!IsPostBack)
            {
                if (Session["EUser"] == null)
                {
                    this.login.Visible = true;
                    this.mainPan.Visible = false;
                }
                else
                {
                    this.login.Visible = false;
                    RecMail();
                    Binding(true);
                }
            }
        }

         public string GetContentStr(object evalContent)
        {
            string s = String.Format("{0}",evalContent);
            if (!String.IsNullOrEmpty(s))
            {
                if (s.Length > 100)
                    s = s.Substring(0, 100) + "..";
            }
            return s;
        }
        public string GetUrl(object evalNo)
        {
            //return String.Format("javascript:zDialog_open0('SendDetail.aspx?OID={0}','发件',600,600,false)", evalNo);
            return String.Format("EMailList.aspx?OID={0}", evalNo);
        }

        public void RecMail()
        {
            //建立邮件接收对象
            jmail.POP3 pop = new POP3();
            //邮件信息借口
            jmail.Message mailMessage=new jmail.Message();
            //建立附件接口
            jmail.Attachment att;
            //建立附件集接口
            jmail.Attachments atts;
            try 
            {
                //有的邮箱并不是接受非SSL端口接收信息，所以绑定邮箱时需要查看此邮箱的SSL是否支持非SSL端口，如果不支持，就填写SSL端口号
                //POP3.Conect(用户名，密码，POP3服务器名称，SSL端口号，非SSL端口号一般默认为110，例如163邮箱);
                string name = Session["EUser"].ToString();
                string pwd = Session["EPwd"].ToString();
                string ser = Session["EServer"].ToString();
                string popName = "";
                //有些邮箱的POP3服务器不一定都是  pop.***.com 格式，有的可能为 pop3.***.com，具体需要去此邮箱中查看
                if (ser == "163.com")
                {
                    popName = "pop.163.com";
                }
                //目前本机测试是不可以的
                if (ser == "qq.com")
                {
                    popName = "pop.qq.com";
                }
                if (ser == "126.com")
                {
                    popName = "pop.126.com";
                }
                pop.Connect(name, pwd, popName, 110);
                //查看POP服务器端是否有邮件
                if (pop.Count > 0)
                {
                    //如果有邮件，循环获取邮件信息;
                    //POP3服务器数据库中的标识是从1开始的
                    for (int i = 1; i <= pop.Count; i++)
                    {
                        //获取邮件完整信息
                        mailMessage = pop.Messages[i];
                        //获取附件信息
                        atts = mailMessage.Attachments;
                        //获取内容字符格式
                        mailMessage.Charset = "gb2312";
                        ///***********
                        ///以下两个属性不建议使用
                        ///有些邮箱不支持或者获取后，邮件内容会出现乱码现象，但是大部分还是可以的
                        
                        //获取编码方式
                        //mailMessage.Encoding = "Base64";
                        //是否使用ISO编码方式
                        //mailMessage.ISOEncodeHeaders = false;

                        ///***********
                        
                        //获取发送人邮箱
                        string sendMail = mailMessage.From;
                        //获取发送人姓名
                        string user = mailMessage.FromName;
                        //获取邮件标题
                        string title = mailMessage.Subject;
                        //获取邮件内容
                        string contect = mailMessage.Body;
                        string AttachFile = null;
                        if (atts.Count >= 1)
                        {
                            for (int k = 0; k < atts.Count; k++)
                            {

                                att = atts[k];//获得附件

                                AttachFile += att.Name;
                            }
                        }


                        //获取邮件接收时间（POP3服务器端）
                        DateTime time = mailMessage.Date;
                        //查询数据中此用户的邮件最近接收的时间
                        DataTable dt = BP.DA.RunSQLReturnTable("select max(ReceiveTime) from OA_MessageInBox where FK_ReceiveUserNo='" + BP.Web.WebUser.No + "'");
                        //如果此用户数据库中存在邮件信息，执行一面代码
                        if (dt.Rows.Count > 1)
                        {
                            //当POP3服务器中接收邮件的时间大于此用户数据库中存在的邮件时间时，将此条邮件信息加入数据库，以避免重复加载邮件信息
                            if (time > Convert.ToDateTime(dt.Rows[0][0].ToString()))
                            {
                                BP.OA.Message.InBox ibox = new BP.OA.Message.InBox();
                                ibox.FK_ReceiveUserNo = BP.Web.WebUser.No;
                                ibox.Sender = user;
                                ibox.Title = title;
                                ibox.AttachFile = AttachFile;
                                ibox.Doc = contect;
                                ibox.AddTime = DateTime.Now;
                                ibox.ReceiveTime = time.ToString();
                                ibox.Received = false;
                                ibox.IsCopy = false;
                                ibox.Insert();
                            }
                        }
                        //如果此用户中没有存在邮件信息
                        else
                        {
                            //将POP3服务器上最近接收的一条邮件存入数据库，以避免加载太多历史邮件信息和初始加载时因空数据造成异常
                            int a = pop.Count - 1;
                            if (dt.Rows.Count < 1)
                            {
                                if (i > a)
                                {
                                    BP.OA.Message.InBox ibox = new BP.OA.Message.InBox();
                                    ibox.FK_ReceiveUserNo = BP.Web.WebUser.No;
                                    ibox.Sender = user;
                                    ibox.Title = title;
                                    ibox.AttachFile = AttachFile;
                                    ibox.Doc = contect;
                                    ibox.AddTime = DateTime.Now;
                                    ibox.ReceiveTime = time.ToString();
                                    ibox.Received = false;
                                    ibox.IsCopy = false;
                                    ibox.Insert();
                                }
                            }
                        }
                    }
                }   
            }             
            catch(Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }
        public void Binding(bool start)
        {
            //需要返回列：No,Content,Geter,RPT
            string sSql = "select OID as No,Title,ReceiveTime as RPT,FK_ReceiveUserNo as Geter,AttachFile from OA_MessageInBox where FK_ReceiveUserNo='" + BP.Web.WebUser.No + "'";
            if (start)
            {
                AspNetPager1.RecordCount = BP.OA.Main.GetPagedRowsCount(sSql);  //第一次需要初始化
                AspNetPager1.PageSize = 10;
                AspNetPager1.CurrentPageIndex = 1;
            }
            this.gridData.DataSource = BP.OA.Main.GetPagedRows(sSql, 0, "Order by No desc", this.AspNetPager1.PageSize, this.AspNetPager1.CurrentPageIndex);
            this.gridData.DataBind();
        }
        protected void GridView1_DataBound(object sender, EventArgs e)
        {
            if (this.gridData.Rows.Count > 0)
                this.gridData.HeaderRow.TableSection = TableRowSection.TableHeader;
        }
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            this.Binding(false);
        }
        protected void BtnLogin_Click(object sender, EventArgs e)
        {
            if (txt_Users.Text != "" && txt_Pwd.Text != "")
            {
                string user = txt_Users.Text.ToString();
                string pwd = txt_Pwd.Text.ToString();
                string[] emser = user.Split('@');
                Session["Ename"] = emser[0];
                Session["EServer"] = emser[1];
                Session["EUser"] = user;
                Session["EPwd"] = pwd;
                RecMail();
                Binding(true);
                this.login.Visible = false;
                this.mainPan.Visible = true;
            }
            else
            {
                this.Alert("请填写邮箱的登录名或密码！");
            }
        }
        protected void Btn2_Click(object sender, EventArgs e)
        {
            this.login.Visible = false;
            this.mainPan.Visible = true;
        }
    }
}